//------------------------------------------------------------
// nebulaGameState.cpp
//------------------------------------------------------------

/**
 * @file nebulaGameState.cpp
 */

#include "nebulaGameState.h"
#include "nebulaApplication.h"
#include "logic/game.h"
#include "gui/nguimanager.h"
#include "input/ninputserver.h"

namespace application {

	CNebulaGameState::CNebulaGameState(CNebulaApplication *app) : CNebulaState(app), game(NULL) {}
	CNebulaGameState::~CNebulaGameState() {}

	void CNebulaGameState::onCreate()
	{
		CNebulaState::onCreate();
	}

	void CNebulaGameState::onDestroy()
	{
		CNebulaState::onDestroy();
	}

	void CNebulaGameState::onActivate()
	{
		CNebulaState::onActivate();

		// Create the game
		game = new logic::CGame();

		// Create the GUIManager
		this->GUIManager = new nebulaGUI::NGUIManager();

		// Register the GUIManager as creation/destruction events observer
		game->addObserver(GUIManager);
		game->init();

		// Register this as game events observer
		game->addObserver(this);

		// Make the scene
		//this->GUIManager->initScene("gfxlib:scene.n2");
		this->GUIManager->initScene("data/gfx/scene.n2");
	}

	void CNebulaGameState::onDeactivate()
	{
		// Unregister observers
		game->removeObserver(this);
		//game->removeObserver(GUIManager);

		// Delete the scene
		//this->GUIManager->endScene();

		// Delete the GUIManager
		delete GUIManager;
		GUIManager = NULL;

		// Delete everything related to the game
		game->end();

		// Delete game
		delete game;
		game = NULL;

		// Deactivate everything from the parent class
		CNebulaState::onDeactivate();
	}

	void CNebulaGameState::onRun()
	{
		CNebulaState::onRun();
		game->update();
	}

	void CNebulaGameState::processUserInput()
	{
        nInputEvent* inputEvent;
        nInputServer *refIS = _nebulaApp->refInputServer;
        for (inputEvent = refIS->FirstEvent(); inputEvent; inputEvent = refIS->NextEvent(inputEvent)) 
		{
            if ((inputEvent->GetType() == N_INPUT_KEY_DOWN) || (inputEvent->GetType() == N_INPUT_KEY_UP)) 
			{
                switch (inputEvent->GetKey()) 
				{
                    case N_KEY_UP:
                        game->insertCommand(logic::ILogicFacade::TCommand(logic::ILogicFacade::CREATEENTITY, inputEvent->GetType() == N_INPUT_KEY_DOWN));
                        break;
				}
			}
		}
	}

	void CNebulaGameState::runLogic() 
	{
		CNebulaState::runLogic();
	}

	void CNebulaGameState::paint3D()
	{
		this->paintAll();
	}

	void CNebulaGameState::processHUDCommand(std::string command)
	{

	}

	void CNebulaGameState::paintAll()
	{
		this->GUIManager->renderScene();
		this->GUIManager->renderEntities();
	}

} // namespace application